package com.wanmait.teatrain.controller;

import com.wanmait.teatrain.utils.AjaxResult;
import com.wanmait.teatrain.utils.BusinessException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class CommonControllerAdvice {

    //针对业务状态代码异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult processBusinessException(BusinessException e){
        return AjaxResult.error(e.getCode(),e.getMessage());
    }

    //参数校验全局异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null) {
            return AjaxResult.error(fieldError.getDefaultMessage());
        }
        return AjaxResult.error("参数校验失败");
    }
}
